﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pampa.CRUD.Security;
using Pampa.MVC.Models;

namespace Pampa.MVC.Security
{
    public class SecurityManagerRules<T> : ISecurityManager
    {
        private readonly Dictionary<string, Func<T, bool>> _viewRules;
        private readonly Dictionary<string, Func<T, bool>> _editRules;

        public SecurityManagerRules()
        {
            _viewRules = new Dictionary<string, Func<T, bool>>();
            _editRules = new Dictionary<string, Func<T, bool>>();
        }

        public void AddViewRule(string permissionId, Func<T, bool> action)
        {
            _viewRules.Add(permissionId, action);
        }

        public void AddEditRule(string permissionId, Func<T, bool> action)
        {
            _editRules.Add(permissionId, action);
        }

        public PermissionType GetPermission(object entity, string action)
        {
            return GetEditorPermission(entity, action);
        }

        public PermissionType GetEditorPermission(object obj, string action)
        {
            var entity = (T) obj;

            if (_viewRules.ContainsKey(action))
            {
                var rule = _viewRules[action];
                if(rule.Invoke(entity))
                {
                    return PermissionType.Edit;
                }
                else
                {
                    return PermissionType.Rejected;
                }
            }
            else if (_editRules.ContainsKey(action))
            {
                var rule = _editRules[action];
                if (rule.Invoke(entity))
                {
                    return PermissionType.Edit;
                }
                else
                {
                    return PermissionType.View;
                }
            }
            else
            {
                return PermissionType.NotApply;
            }
        }
    }
}
